package com.smart.manager.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.smart.common.entities.ajax.AjaxResult;
import com.smart.common.entities.constant.ExceptionTips;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.common.entities.core.Page;
import com.smart.manager.system.entities.body.RSystemScheduleTask;
import com.smart.manager.system.entities.models.SystemScheduleTask;
import com.smart.manager.system.repository.ScheduleTaskRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.List;


/**
 * @author Administrator
 */

@Api(tags = "任务管理")
@RestController
@RequestMapping(SmartConstant.MANAGER_API_PREFIX + "system/schedule/task")
@RequiredArgsConstructor
public class ScheduleTaskApi {

    private final ScheduleTaskRepository scheduleTaskRepository;

    @GetMapping(value = "pageList")
    @ApiOperation(value = "查询任务")
    @SaCheckPermission("system:schedule:task:pageList")
    public AjaxResult<Page<SystemScheduleTask>> pageList(@Validated RSystemScheduleTask.SearchBody body) {
        Page<SystemScheduleTask> result = scheduleTaskRepository.pageList(body);
        return AjaxResult.data(result);
    }





    @PostMapping("add")
    @ApiOperation(value = "新增任务")
    @ApiOperationSupport(order = 2)
    @SaCheckPermission("system:schedule:task:add")
    public AjaxResult<String> add(@RequestBody @Validated RSystemScheduleTask.EditBody data) {
        scheduleTaskRepository.save(data);
        return AjaxResult.success();

    }


    @PutMapping("update/{id}")
    @ApiOperation(value = "修改任务")
    @ApiOperationSupport(order = 3)
    @SaCheckPermission("system:schedule:task:update")
    public AjaxResult<String> update(@PathVariable Long id, @RequestBody @Validated RSystemScheduleTask.EditBody data) {
        scheduleTaskRepository.update(id, data);
        return AjaxResult.success();
    }


    @DeleteMapping("delete")
    @ApiOperation(value = "删除任务")
    @ApiOperationSupport(order = 4)
    @SaCheckPermission("system:schedule:task:delete")
    public AjaxResult<Integer> delete(@RequestBody @NotEmpty(message = ExceptionTips.PK_EMPTY) List<Long> idList) {
        int i = scheduleTaskRepository.removeByIdList(idList);
        return AjaxResult.delSuccess(i);
    }


    @PostMapping("run/{id}")
    @ApiOperation(value = "手动执行")
    @ApiOperationSupport(order = 5)
    @SaCheckPermission("system:schedule:task:runNow")
    public AjaxResult<String> runNow(@PathVariable Long id) {
        scheduleTaskRepository.runNow(id);
        return AjaxResult.success();
    }




}
